<template>
  <div class="setting-container">
    <el-card>
      <!-- 导航 -->
      <div slot="header">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人设置</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 栅格 -->
      <el-row>
        <el-col :span="12">
          <!-- 表单 -->
          <el-form label-width="120px">
            <el-form-item label="编号：">{{userInfo.id}}</el-form-item>
            <el-form-item label="手机：">{{userInfo.mobile}}</el-form-item>
            <el-form-item label="媒体名称：">
              <el-input v-model="userInfo.name"></el-input>
            </el-form-item>
            <el-form-item label="媒体简介：">
              <el-input v-model="userInfo.intro" type="textarea" :rows="3"></el-input>
            </el-form-item>
            <el-form-item label="联系邮箱：">
              <el-input v-model="userInfo.email"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="upDateInfo" type="primary">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12">
          <div class="avatar-edit" @click="openCropper">
            <el-image v-if="userInfo.photo" :src="userInfo.photo" class="avatar" ></el-image>
            <div v-else class="upload-box">
              <el-button type="primary" class="select-btn">选择图片</el-button>
            </div>
          </div>

          <!-- 上传组件 action必须属性-->
          <el-dialog
            class="cropper-dialog"
            :close-on-click-modal="false"
            :visible="showCropper"
            :append-to-body="true"
            center
            @close="close"
            width="35%"
          >
            <div slot="title" class="dialog-title">
              <span class="dialog-line"></span>
              <span>头像裁切</span>
            </div>
          <el-upload
            action="任意字符,但必须有"
            :before-upload="beforeAvatarUpload"
            class="avatar-uploader"
            :auto-upload="true"
            :on-change="preImg"
            :show-file-list="false"
            name="image"
          >
          <el-button type="primary" class="select-btn" icon="el-icon-upload" size="mini">请选择图片</el-button>
          </el-upload>
            <div class="cropper-wrap">
              <div class="cropper-box" :style="cropperStyle">
                <div class="preview-title">
                  <span>预览</span>
                </div>
                <vue-cropper
                  ref="cropper"
                  :img="option.img"
                  :output-size="option.size"
                  :output-type="option.outputType"
                  :info="option.info"
                  :full="option.full"
                  :canScale="option.canScale"
                  :can-move="option.canMove"
                  :can-move-box="option.canMoveBox"
                  :fixed="option.fixed"
                  :fixed-box="option.fixedBox"
                  :original="option.original"
                  :auto-crop="option.autoCrop"
                  :auto-crop-width="option.autoCropWidth"
                  :auto-crop-height="option.autoCropHeight"
                  :center-box="option.centerBox"
                  :high="option.high"
                  :info-true="option.infoTrue"
                  :max-img-size="option.maxImageSize"
                  :enlarge="option.enlarge"
                  :mode="option.mode"
                  :maxImgSize="option.maxImgSize"
                  @realTime="realTime"
                />
              </div>
              <div class="preview-box">
                <input
                  ref="upload"
                  type="file"
                  style="position:absolute; clip:rect(0 0 0 0);"
                  accept="image/png, image/jpeg, image/jpg"
                  @change="uploadImg"
                />
                <div :style="previewStyle" class="preview-img">
                  <!-- <div v-html="preview"> -->
                  <div :style="preview.div">
                    <img :style="preview.img" :src="preview.url" />
                  </div>
                </div>
              </div>
            </div>
            <div slot="footer" class="dialog-footer">
              <!-- <el-button @click="close">取 消</el-button>-->
              <el-button-group>
                <el-button type="primary" @click="rotateLeft" icon="el-icon-refresh-left" round></el-button>
                <el-button type="primary" @click="rotateRight" icon="el-icon-refresh-right" round></el-button>
                <el-button type="primary" @click="finish" icon="el-icon-circle-check" round></el-button>
              </el-button-group>
            </div>
          </el-dialog>
          <p class="edit-photo">修改头像</p>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import { getInfo, upAvatar, upInfo } from '@/api/user'
import { VueCropper } from 'vue-cropper'
export default {
  name: 'setting',
  data () {
    return {
      // 用户信息
      userInfo: {
        id: '', // id
        intro: '', // 介绍
        email: '', // 邮箱
        mobile: '', // 手机号
        name: '', // 名字
        photo: '' // 头像
      },
      canCropper: false, // 表示头像校验是否通过
      showCropper: false, // 裁切区是否显示
      option: {
        img: '', // 裁剪图片的地址
        outputSize: 1, // 裁剪生成图片的质量
        outputType: 'png', // 裁剪生成图片的格式
        full: true, // 是否输出原图比例的截图
        info: true, // 图片大小信息
        canScale: true, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 150, // 默认生成截图框宽度
        autoCropHeight: 150, // 默认生成截图框高度
        canMove: true, // 上传图片是否可以移动
        fixedBox: true, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        canMoveBox: true, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: true, // 截图框是否被限制在图片里面
        height: true,
        infoTrue: false, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
        enlarge: 1, // 图片根据截图框输出比例倍数
        mode: 'container', // 图片默认渲染方式
        maxImgSize: 375 // 限制图片最大宽度和高度
      },
      cropperStyle: 'width:280px;height:280px', // 裁剪框样式
      previewStyle: {
        width: '150px',
        height: '150px',
        overflow: 'hidden',
        zoom: '0.75',
        position: 'relative',
        top: '-352px',
        left: '460px',
        'border-radius': '50%'
      }, // 预览区样式
      // upload: '', // 重新上传事件
      preview: {},
      blod: ''
    }
  },
  methods: {
    hGetInfo () {
      // 获取用户信息
      getInfo().then(res => {
        this.userInfo = res.data.data
      })
    },
    upDateInfo () {
      // 修改资料
      this.eventBus.$emit('setUserName', this.userInfo.name)
      upInfo(this.userInfo.name, this.userInfo.intro, this.userInfo.email)
        .then(res => {
          this.hGetInfo()
          this.$message({ type: 'success', message: '修改资料成功' })
        })
        .catch(err => {
          console.log(err)
          this.$message({ type: 'success', message: '修改失败' })
        })
    },
    beforeAvatarUpload (file) {
      // 1.上传前的校验
      const isLt2M = file.size / 1024 / 1024 < 2 // byte除1024等于kb再处于1024等于mb
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      this.canCropper = isLt2M // 校验成功后裁切弹框显示
      return false // 返回false 然后自己去触发上传
    },
    preImg (file) {
      // 2.裁切区域 图片传进来会触发
      this.blod = file
      this.$nextTick(() => {
        if (this.canCropper) {
          this.userInfo.photo = window.URL.createObjectURL(file.raw) // 将图片转化为路径
          this.showCropper = this.canCropper
          this.option.img = this.userInfo.photo
        }
      })
    },
    close () {
      // 点击取消关闭对话框
      this.showCropper = false
    },
    realTime (data) {
      // 裁切预览 每次移动裁切框会触发
      this.preview = {
        ...data
      }
    },
    uploadImg () {
      console.log(3)
    },
    finish () {
      this.$refs.cropper.getCropData(data => {
        // 将base64转换为文件
        const dataURLtoFile = function (dataurl, filename) {
          var arr = dataurl.split(',')
          var mime = arr[0].match(/:(.*?);/)[1]
          var bstr = atob(arr[1])
          var n = bstr.length
          var u8arr = new Uint8Array(n)
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
          }
          return new File([u8arr], filename, { type: mime })
        }

        // 调用接口
        this.eventBus.$emit('setUserPhoto', data)
        const formData = new FormData()
        formData.append('photo', dataURLtoFile(data, this.blod.name))
        upAvatar(formData)
          .then(res => {
            this.$message({ type: 'success', message: '上传头像成功' })
            this.hGetInfo()
            this.showCropper = false
          })
          .catch(() => {
            this.$message({ type: 'success', message: '上传头像失败' })
            this.hGetInfo()
            this.eventBus.$emit('setUserPhoto', this.userInfo.photo) // 调用事件车 更新头部组件信息
          })
      })
    },
    rotateLeft () {
      this.$refs.cropper.rotateLeft()
    },
    rotateRight () {
      this.$refs.cropper.rotateRight()
    },
    openCropper () {
      this.showCropper = true
      this.option.img = this.userInfo.photo
    }
  },
  components: {
    VueCropper
  },
  mounted () {
    this.hGetInfo()
  }
}
</script>

<style scoped lang='less'>
.preview-box {
  height: 0px;
}
.avatar-edit{
  // position: relative;
  width: 180px;
  left: 220px;
  // height: 178px;
  // line-height: 178px;
   text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.dialog-title{
  position: relative;
  text-indent: 1em;
  text-align: left;
  color: #00a8ff;
  .dialog-line{
    position: absolute;
    display: block;
    width: 2px;
    height: 15px;
    top: 3px;
    left: 5px;
background-color: #00a8ff;
  }
}
.avatar {
  border-radius: 4px;
  top:3px;
  position: relative;
  width: 178px;
  height: 178px;
  line-height: 178px;
}
.avatar-uploader {
  // text-align: center;
  margin-top: -30px;
}
// .avatar-uploader-icon {
//   font-size: 28px;
//   color: #8c939d;
//   width: 178px;
//   height: 178px;
//   line-height: 178px;
//   text-align: center;
// }
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.edit-photo {
  font-size: 12px;
  text-align: center;
}
</style>
